#include<iostream>
using namespace std;
const int N = 1e4 + 10;
int arr[60];
int n, m, q;
int f[N];
int main()
{
	while (cin >> n) {
		for (int i = 0; i < n; i++) {
			cin >> m;
			int ans = 0;
			for (int j = 0; j < m; j++) {
				cin >> arr[j];
				ans |= arr[j];
			}
			for (int j = 0; j < m; j++) {
				f[arr[j]] |= ans;
			}
		}
		cin >> q;
		while (q--) {
			int x, y;
			int cnt = 0;
			cin >> x >> y;
			int ans1 = x;
			bool flag1 = 0, flag2 = 0;
			for (int i = 0; i < 31; i++) {
				if ((f[x] >> i) == 1 && (f[y] >> i) == 1)cnt++;
				if ((f[x] >> i) == 1 && (y >> i) == 1)flag1 = 1;
				if ((f[y] >> i) == 1 && (x >> i) == 1)flag2 = 1;
			}
			if (flag1 + flag2 == 2)cnt--;
			cout << cnt << endl;
		}
	}
	return 0;
}